package com.google.code.p.slideunlocker;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsoluteLayout.LayoutParams;
import easing.interpolator.BackInterpolator;
import easing.interpolator.BounceInterpolator;
import easing.interpolator.CircInterpolator;
import easing.interpolator.CubicInterpolator;
import easing.interpolator.ElasticInterpolator;
import easing.interpolator.ExpoInterpolator;
import easing.interpolator.QuadInterpolator;
import easing.interpolator.QuartInterpolator;
import easing.interpolator.QuintInterpolator;
import easing.interpolator.SineInterpolator;
import easing.interpolator.EasingType.Type;

public class SlideUnlocker extends Activity
{

    private SlidableButton myButton;
    private TextView smallTxt;
    private TextView bigTxt;
    private MaskedTextView txt;
    private View all;
    
    private int position = 0;
    private Interpolator interpolator;
    private Timer clock;
    
    private Handler handler;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("EEEEE, MMMMMM dd");
    private SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a");
    private ImageView background;
    private Drawable iphone;
    private VersionChecker versionChecker = null;

    private PackageManager pm;
    
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        txt.setStart(hasFocus);
    }
    
    @Override
    protected void onStop() {
      super.onStop();
      
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        pm = getPackageManager();
        pm.addPackageToPreferred(getPackageName());
        
        versionChecker = new VersionChecker(this);
        versionChecker.checkVersionAvailable();
        
        iphone = getResources().getDrawable(R.drawable.iphone);
        myButton = (SlidableButton) findViewById(R.id.btn); 
        myButton.setGravity(Gravity.BOTTOM);
        txt = (MaskedTextView) findViewById(R.id.txt);
        LayoutParams lp = (LayoutParams) txt.getLayoutParams();
        lp.x=100;
        lp.y=390;
        txt.setLayoutParams(lp);
        myButton.setTxt(txt);
        
        background = (ImageView) findViewById(R.id.background);
        smallTxt = (TextView) findViewById(R.id.smalltxt);
        bigTxt = (TextView) findViewById(R.id.bigtxt);
        all = findViewById(R.id.all);
        handler = new Handler(){
          @Override
          public void handleMessage(Message msg) {
            Date now = new Date(System.currentTimeMillis());
            String min = String.valueOf(now.getMinutes());
            String sec = String.valueOf(now.getSeconds());
            if(min.length()==1){
              min = "0"+min;
            }
            if(sec.length() == 1){
              sec = "0"+sec;
            }
            bigTxt.setText(timeFormat.format(now));
            smallTxt.setText(dateFormat.format(now));
          }
        };
        
        
    }
    

    private void startBackgroundService(){
      startService(new Intent(this, SleepListenService.class));
    }
    
    private void stopBackgroundService(){
      stopService(new Intent(this, SleepListenService.class));
    }
    
    
    @Override
    protected void onStart() {
      super.onStart();
      initClock();
      
    }
    
    private void initClock(){
      if(clock!=null)
        clock.cancel();
      clock = new Timer();
      clock.schedule(new TimerTask(){

        @Override
        public void run() {
          handler.sendEmptyMessage(0);
        }
        
      }, 0, 1000);
    }
    
    
    @Override
    protected void onPause() {
      
      super.onPause();
    }
    
    private boolean wallpaper = false;
    
    @Override
    protected void onResume() {
      initClock();
      //get the user preferences
      SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
      wallpaper = settings.getBoolean("wallpaper", false);
      if(wallpaper){
        Drawable wp = getWallpaper();
        background.setImageDrawable(wp);
      }else{
        background.setImageDrawable(iphone);
      }
      boolean autolock = settings.getBoolean("autolock", true);
      if(autolock){
        startBackgroundService();
      }
      String btn = settings.getString("button", "Grey");
      Drawable btnDrawable = null;
      if("Grey".equalsIgnoreCase(btn)){ 
        btnDrawable = getResources().getDrawable(R.drawable.btn_grey);
      }else if("Standard".equalsIgnoreCase(btn)){ 
          btnDrawable = getResources().getDrawable(R.drawable.btn_iphone);
      }else if("Black".equalsIgnoreCase(btn)){ 
          btnDrawable = getResources().getDrawable(R.drawable.btn_black);
      }else if("Blue".equalsIgnoreCase(btn)){ 
          btnDrawable = getResources().getDrawable(R.drawable.btn_blue);
      }else if("Green".equalsIgnoreCase(btn)){ 
          btnDrawable = getResources().getDrawable(R.drawable.btn_green);
      }else if("Orange".equalsIgnoreCase(btn)){ 
          btnDrawable = getResources().getDrawable(R.drawable.btn_orange);
      }else if("Purple".equalsIgnoreCase(btn)){ 
          btnDrawable = getResources().getDrawable(R.drawable.btn_purple);
      }else if("Red".equalsIgnoreCase(btn)){ 
          btnDrawable = getResources().getDrawable(R.drawable.btn_red);
      }else if("Yellow".equalsIgnoreCase(btn)){ 
          btnDrawable = getResources().getDrawable(R.drawable.btn_yellow);
      }else{
        btnDrawable = getResources().getDrawable(R.drawable.btn_grey);
      }
      myButton.setBackgroundDrawable(btnDrawable);
      super.onResume();
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
      super.onConfigurationChanged(newConfig);
    }

    
    @Override
    public boolean onTouchEvent(final MotionEvent event) {
      if(event.getAction() == MotionEvent.ACTION_UP && myButton.isDragging()){
        
        myButton.setDragging(false);
        LayoutParams lp = (LayoutParams) myButton.getLayoutParams();

        if(event.getX() > 265f){
          pm.removePackageFromPreferred(getPackageName());
          AlphaAnimation alpha = new AlphaAnimation(1, 0);
          alpha.setDuration(600);
          alpha.setFillAfter(true);
          
          alpha.setAnimationListener(new AnimationListener(){

            @Override
            public void onAnimationEnd(Animation animation) {
              SlideUnlocker.this.finish();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {}

            @Override
            public void onAnimationStart(Animation animation) {}
            
          });
         
          all.startAnimation(alpha);
        }else{
          
          TranslateAnimation trans1 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.ABSOLUTE, 0-lp.x,
              Animation.RELATIVE_TO_SELF, 0, Animation.ABSOLUTE, 0);
          trans1.setStartOffset(0);
          trans1.setDuration(500);
          trans1.setFillBefore(true);
          
          if(interpolator!=null){
            trans1.setInterpolator(interpolator);
          }
          
          trans1.setAnimationListener(new AnimationListener(){

            @Override
            public void onAnimationEnd(Animation animation) {
              myButton.setAnimating(false);
              myButton.setDragging(false);
              LayoutParams lp = (LayoutParams) myButton.getLayoutParams();
              lp.x = 0;
              myButton.setLayoutParams(lp);
              txt.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {}

            @Override
            public void onAnimationStart(Animation animation) {
              myButton.setAnimating(true);
            }
            
          });
          myButton.startAnimation(trans1);          
        }

      }else{
        myButton.setX(Math.min(210, Math.max(0, (int)event.getX()-30)));
      }
      return false;
    }
    
    private void showMessage(String errorString) {
      Toast text = Toast.makeText(this, 
              errorString, Toast.LENGTH_SHORT);
      text.show();
  }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        
        if(keyCode == KeyEvent.KEYCODE_MENU){
            return super.onKeyDown(keyCode, event);
        }
        
        if(keyCode == KeyEvent.KEYCODE_BACK){
         position = ++position % 29;

         switch (position) {
         case 0:
           interpolator = new BackInterpolator(Type.IN, 0);
           break;
         case 1:
           interpolator = new BackInterpolator(Type.OUT, 0);
           break;
         case 2:
           interpolator = new BackInterpolator(Type.INOUT, 0);
           break;
         case 3:
           interpolator = new ElasticInterpolator(Type.IN, 1, 0.3f);
           break;
         case 4:
           interpolator = new ElasticInterpolator(Type.OUT, 1, 0.3f);
           break;
         case 5:
           interpolator = new ElasticInterpolator(Type.INOUT, 1, 0.3f);
           break;
         case 6:
           interpolator = new BounceInterpolator(Type.IN);
           break;
         case 7:
           interpolator = new BounceInterpolator(Type.OUT);
           break;
         case 8:
           interpolator = new BounceInterpolator(Type.INOUT);
           break;
         case 9:
           interpolator = new CircInterpolator(Type.IN);
           break;
         case 10:
           interpolator = new CircInterpolator(Type.OUT);
           break;
         case 11:
           interpolator = new CircInterpolator(Type.INOUT);
           break;
         case 12:
           interpolator = new ExpoInterpolator(Type.IN);
           break;
         case 13:
           interpolator = new ExpoInterpolator(Type.OUT);
           break;
         case 14:
           interpolator = new ExpoInterpolator(Type.INOUT);
           break;
         case 15:
           interpolator = new QuadInterpolator(Type.IN);
           break;
         case 16:
           interpolator = new QuadInterpolator(Type.OUT);
           break;
         case 17:
           interpolator = new QuadInterpolator(Type.INOUT);
           break;
         case 18:
           interpolator = new CubicInterpolator(Type.IN);
           break;
         case 19:
           interpolator = new CubicInterpolator(Type.OUT);
           break;
         case 20:
           interpolator = new CubicInterpolator(Type.INOUT);
           break;
         case 21:
           interpolator = new QuartInterpolator(Type.IN);
           break;
         case 22:
           interpolator = new QuartInterpolator(Type.OUT);
           break;
         case 23:
           interpolator = new QuartInterpolator(Type.INOUT);
           break;
         case 24:
           interpolator = new QuintInterpolator(Type.IN);
           break;
         case 25:
           interpolator = new QuintInterpolator(Type.OUT);
           break;
         case 26:
           interpolator = new QuintInterpolator(Type.INOUT);
           break;
         case 27:
           interpolator = new SineInterpolator(Type.IN);
           break;
         case 28:
           interpolator = new SineInterpolator(Type.OUT);
           break;
         case 29:
           interpolator = new SineInterpolator(Type.INOUT);
           break;
         default:
           break;
         }
         switch (position) {
         case 0:
           showMessage("slider effect "+position+" BackInterpolator(Type.IN, 0)");
           break;
         case 1:
           showMessage("slider effect "+position+" BackInterpolator(Type.OUT, 0)");
           break;
         case 2:
           showMessage("slider effect "+position+" BackInterpolator(Type.INOUT, 0)");
           break;
         case 3:
           showMessage("slider effect "+position+" ElasticInterpolator(Type.IN, 1, 0.3f)");
           break;
         case 4:
           showMessage("slider effect "+position+" ElasticInterpolator(Type.OUT, 1, 0.3f)");
           break;
         case 5:
           showMessage("slider effect "+position+" ElasticInterpolator(Type.INOUT, 1, 0.3f)");
           break;
         case 6:
           showMessage("slider effect "+position+" BounceInterpolator(Type.IN)");
           break;
         case 7:
           showMessage("slider effect "+position+" BounceInterpolator(Type.OUT)");
           break;
         case 8:
           showMessage("slider effect "+position+" BounceInterpolator(Type.INOUT)");
           break;
         case 9:
           showMessage("slider effect "+position+" CircInterpolator(Type.IN)");
           break;
         case 10:
           showMessage("slider effect "+position+" CircInterpolator(Type.OUT)");
           break;
         case 11:
           showMessage("slider effect "+position+" CircInterpolator(Type.INOUT)");
           break;
         case 12:
           showMessage("slider effect "+position+" ExpoInterpolator(Type.IN)");
           break;
         case 13:
           showMessage("slider effect "+position+" ExpoInterpolator(Type.OUT)");
           break;
         case 14:
           showMessage("slider effect "+position+" ExpoInterpolator(Type.INOUT)");
           break;
         case 15:
           showMessage("slider effect "+position+" QuadInterpolator(Type.IN)");
           break;
         case 16:
           showMessage("slider effect "+position+" QuadInterpolator(Type.OUT)");
           break;
         case 17:
           showMessage("slider effect "+position+" QuadInterpolator(Type.INOUT)");
           break;
         case 18:
           showMessage("slider effect "+position+" CubicInterpolator(Type.IN)");
           break;
         case 19:
           showMessage("slider effect "+position+" CubicInterpolator(Type.OUT)");
           break;
         case 20:
           showMessage("slider effect "+position+" CubicInterpolator(Type.INOUT)");
           break;
         case 21:
           showMessage("slider effect "+position+" QuartInterpolator(Type.IN)");
           break;
         case 22:
           showMessage("slider effect "+position+" QuartInterpolator(Type.OUT)");
           break;
         case 23:
           showMessage("slider effect "+position+" QuartInterpolator(Type.INOUT)");
           break;
         case 24:
           showMessage("slider effect "+position+" QuintInterpolator(Type.IN)");
           break;
         case 25:
           showMessage("slider effect "+position+" QuintInterpolator(Type.OUT)");
           break;
         case 26:
           showMessage("slider effect "+position+" QuintInterpolator(Type.INOUT)");
           break;
         case 27:
           showMessage("slider effect "+position+" SineInterpolator(Type.IN)");
           break;
         case 28:
           showMessage("slider effect "+position+" SineInterpolator(Type.OUT)");
           break;
         case 29:
           showMessage("slider effect "+position+" SineInterpolator(Type.INOUT)");
           break;
         default:
           break;
         }
       }
       return true;
    }
    
    
    private static final int HOME_ID = Menu.FIRST;
    private static final int PREFERENCE_ID = Menu.FIRST+1;
    private static final int STOP_SERVICE_ID = Menu.FIRST+2;
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        menu.add(0, HOME_ID, 0, "Home Screen").setIcon(R.drawable.home_icon).setOnMenuItemClickListener(new OnMenuItemClickListener(){

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                pm.removePackageFromPreferred(getPackageName());
                Intent i = new Intent(Intent.ACTION_MAIN);
                i.addCategory(Intent.CATEGORY_HOME);
                i.setClassName("com.android.launcher", "com.android.launcher.Launcher");
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
                finish();
                return true;
            }
            
        });
        menu.add(1, PREFERENCE_ID, 0, "Settings").setIcon(R.drawable.settings).setOnMenuItemClickListener(new OnMenuItemClickListener(){

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Intent launchPreferencesIntent = new Intent(SlideUnlocker.this, Preferences.class);
                
                // Make it a subactivity so we know when it returns
                startActivityForResult(launchPreferencesIntent, 1);
                return true;
            }
            
        });
        menu.add(2, STOP_SERVICE_ID, 0, "Stop background service").setIcon(android.R.drawable.ic_delete).setOnMenuItemClickListener(new OnMenuItemClickListener(){

          @Override
          public boolean onMenuItemClick(MenuItem item) {
              stopBackgroundService();
              return true;
          }
          
      });
        
        return true;
    }
}
